﻿using Furion.DynamicApiController;
using Furion.UnifyResult;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using MSEAP.Entitys;
using MSEAP.VO.Admin;
using SqlSugar;

namespace MSEAP.Controllers
{
    [DynamicApiController]
    public class AdminController
    {
        private readonly ILogger<AdminController> logger;
        private readonly ISqlSugarClient db;

        public AdminController(ILogger<AdminController> logger, ISqlSugarClient db)
        {
            this.db = db;
            this.logger = logger;
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] ListVO vo)
        {
            RefAsync<int> total = 0;
            List<UserEntity> users = await db.Queryable<UserEntity>()
                .Where(ue => ue.Id != 1) // 排除超级管理员
                .Where(ue => ue.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(vo.Content), ue => ue.UserName.Contains(vo.Content) || ue.RealName.Contains(vo.Content))
                .ToPageListAsync(vo.PageIndex, vo.PageSize, total);

            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = users,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] SaveVO vo)
        {
            // 判断用户是否存在
            UserEntity user = await db.Queryable<UserEntity>()
                .Where(u => u.IsActive == 1)
                .Where(u => u.UserName == vo.UserName)
                .SingleAsync();
            if (user != null)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该用户已存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            await db.Insertable<UserEntity>(vo.Adapt<UserEntity>()).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = vo,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] DeleteVO vo)
        {
            await db.Updateable<UserEntity>().SetColumns(u => u.IsActive == 0).Where(u => u.Id == vo.Id).Where(u => u.Id != 1).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] UpdateVO vo)
        {
            // 判断用户是否存在
            bool hasAny = await db.Queryable<UserEntity>()
                .Where(u => u.IsActive == 1)
                .Where(u => u.UserName == vo.UserName)
                .Where(u => u.Id != vo.Id)
                .AnyAsync();
            if (hasAny)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该账户已存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            await db.Updateable<UserEntity>(vo).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = vo,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看用户
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] ShowVO vo)
        {
            UserEntity user = await db.Queryable<UserEntity>()
                .Where(u => u.IsActive == 1)
                .InSingleAsync(vo.Id);

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = user,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
